package pers.ree.demo.concurrent;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchDemo {

    public static void main(String[] args) {
        HttpClient client = HttpClient.newHttpClient();
        final int numRequests = 10;
        ExecutorService executorService = Executors.newFixedThreadPool(numRequests);
        final CountDownLatch startSignal = new CountDownLatch(1);
        final CountDownLatch doneSignal = new CountDownLatch(numRequests);

        final long productId = 21L;

        for (int i = 1; i <= numRequests; i++) {
            executorService.submit(() -> {
                try {
                    startSignal.await(); // 等待所有线程都准备好
                    sendPutRequest(client, "http://localhost:9680/zk-product/product/reduce/stock/" + productId);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    doneSignal.countDown(); // 完成任务后计数减一
                }
            });
        }

        startSignal.countDown(); // 触发所有线程开始工作
        try {
            doneSignal.await(); // 等待所有任务完成
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown(); // 关闭线程池
        }
    }

    private static void sendPutRequest(HttpClient client, String url) throws Exception {
        URI uri = new URI(url);
        HttpRequest request = HttpRequest.newBuilder()
                .uri(uri)
                .PUT(HttpRequest.BodyPublishers.noBody())
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println("Response for URL " + url + ": " + response.statusCode()+ ", body: " + response.body());
    }

    /*
    * 只用一个CountDownLatch的写法
    * */
//    private static final HttpClient httpClient = HttpClient.newHttpClient();
//
//    public static void main(String[] args) throws Exception {
//        int requestCount = 10; // 假设同时发起10个请求
//        CountDownLatch latch = new CountDownLatch(requestCount);
//        ExecutorService executor = Executors.newFixedThreadPool(requestCount);
//        List<Resp<String>> responses = new ArrayList<>();
//
//        for (int i = 0; i < requestCount; i++) {
//            int finalI = i;
//            executor.submit(() -> {
//                try {
//                    latch.await(); // 等待所有线程到达此点
//                    makeHttpRequest("http://example.com", finalI, responses);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            });
//            latch.countDown(); // 减少计数，表示一个线程已经准备好
//        }
//
//        latch.await(); // 等待所有线程到达等待点，此时计数应为0
//        executor.shutdown();
//        if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
//            executor.shutdownNow();
//        }
//
//        // 打印响应或处理响应
//        responses.forEach(resp -> {
//            if (resp.success()) {
//                System.out.println("Request succeeded with data: " + resp.getData());
//            } else {
//                System.out.println("Request failed with message: " + resp.getMsg());
//            }
//        });
//    }
//
//    private static void makeHttpRequest(String url, int requestId, List<Resp<String>> responses) throws Exception {
//        HttpRequest request = HttpRequest.newBuilder()
//                .uri(new URI(url))
//                .header("User-Agent", "Java 11 HttpClient Bot")
//                .build();
//
//        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
//        int statusCode = response.statusCode();
//        String responseBody = response.body();
//
//        // 使用Resp类封装响应
//        Resp<String> resp = new Resp<>(statusCode, "status", "HTTP response for request " + requestId, responseBody);
//        responses.add(resp);
//    }
}
